package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private MiniMapper miniMapper;

    public RequestProcessor(Socket socket, MiniMapper miniMapper) {
        this.socket = socket;
        this.miniMapper = miniMapper;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            int i = request.getUrl().indexOf("/", 1);
            String projectName = request.getUrl().substring(1,i); //项目名
            String uri = request.getUrl().substring(i); //uri


            if(miniMapper.getHosts().size()>0 &&
                    miniMapper.getHosts().containsKey(projectName)){
                MiniContext miniContext = miniMapper.getHosts().get(projectName);

                if(miniContext.getServletMap().get(uri) !=null){
                    MiniWrapper miniWrapper = miniContext.getServletMap().get(uri);
                    HttpServlet httpServlet = miniWrapper.getHttpServlet();
                    httpServlet.service(request,response);
                }else{
                    String absoluteResourcePath = miniMapper.getAppBase()+ request.getUrl();
                    response.outHtml(absoluteResourcePath);
                }
            }else{
                response.output(HttpProtocolUtil.getHttpHeader404()); //项目不存在
            }





            /*
            // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }
            */

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
